<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>RF客户价值分析 (Recency & Frequency)</h3>
      <div class="controls">
        <div class="analysis-type-selector">
          <label>分析视图：</label>
          <select v-model="viewType" @change="updateChart">
            <option value="chart">分类图表</option>
            <option value="table">统计表格</option>
          </select>
        </div>
      </div>
    </div>
    
    <!-- 图表视图 -->
    <div v-if="viewType === 'chart'" ref="chart" style="width: 100%; height: 500px;"></div>
    
    <!-- 数据表格视图 -->
    <div v-else class="rf-table">
      <div class="table-header">
        <h4>RF客户细分详情</h4>
        <div class="table-stats">
          <span>总用户数: {{ totalUsers }}</span>
          <span>高价值用户: {{ highValueUsers }}</span>
        </div>
      </div>
      <div class="table-scroll-wrapper">
        <table>
          <thead>
            <tr>
              <th>客户类型</th>
              <th>用户数量</th>
              <th>占比(%)</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in tableData" :key="item.userType" 
                :class="getUserSegmentClass(item.userType)">
              <td>{{ item.userType }}</td>
              <td>{{ item.userCnt }}</td>
              <td>{{ item.percentage }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 客户细分统计卡片 -->
    <div class="segment-stats">
      <h4>客户细分统计</h4>
      <div class="stats-grid">
        <div v-for="item in tableData" :key="item.userType" 
             :class="['stat-card', getSegmentClass(item.userType)]">
          <div class="stat-value">{{ item.userCnt }}</div>
          <div class="stat-label">{{ item.userType }}</div>
          <div class="stat-percentage">{{ item.percentage }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, watch, onUnmounted, computed } from 'vue';

export default {
  name: 'RFMAnalysis',
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chart = ref(null);
    let myChart = null;
    const viewType = ref('chart');

    // 处理RFM数据
    const rfmData = computed(() => {
      if (!props.chartData || props.chartData.length === 0) {
        return [];
      }
      
      // 计算总数
      const total = props.chartData.reduce((sum, item) => sum + Number(item.userCnt || 0), 0);
      
      // 转换数据格式
      return props.chartData.map(item => ({
        userType: item.userType || '',
        userCnt: Number(item.userCnt || 0),
        percentage: total > 0 ? ((Number(item.userCnt || 0) / total) * 100).toFixed(2) + '%' : '0.00%'
      }));
    });

    // 表格数据
    const tableData = computed(() => {
      return rfmData.value;
    });

    // 统计信息
    const totalUsers = computed(() => {
      return rfmData.value.reduce((sum, item) => sum + item.userCnt, 0);
    });
    
    const highValueUsers = computed(() => {
      const highValue = rfmData.value.find(item => item.userType === '价值客户');
      return highValue ? highValue.userCnt : 0;
    });

    // 样式类
    const getSegmentClass = (segment) => {
      const classMap = {
        '价值客户': 'high-value',
        '发展客户': 'active',
        '保持客户': 'loyal',
        '挽留客户': 'churn-risk'
      };
      return classMap[segment] || 'general';
    };

    const getUserSegmentClass = (segment) => {
      return `user-${getSegmentClass(segment)}`;
    };

    const initChart = () => {
      if (!chart.value) return;
      
      // 销毁旧的图表实例（如果存在）
      if (myChart) {
        myChart.dispose();
      }
      
      myChart = echarts.init(chart.value);
      
      const data = rfmData.value;
      
      if (data.length === 0) {
        myChart.setOption({
          title: {
            text: '暂无RF分析数据',
            left: 'center',
            top: 'center'
          }
        });
        return;
      }
      
      const labels = data.map(item => item.userType);
      const values = data.map(item => item.userCnt);
      const percentages = data.map(item => item.percentage);
      
      const option = {
        // title: {
        //   text: 'RF客户分布',
        //   left: 'center'
        // },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `${labels[params.dataIndex]}: ${values[params.dataIndex]}人 (${percentages[params.dataIndex]})`;
          }
        },
        legend: {
          bottom: 10,
          left: 'center',
          data: labels
        },
        series: [{
          name: '用户数量',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data.map(item => ({
            value: item.userCnt,
            name: item.userType,
            itemStyle: {
              color: getSegmentColor(item.userType)
            }
          }))
        }]
      };
      
      myChart.setOption(option);
    };

    // 获取细分颜色
    const getSegmentColor = (segment) => {
      const colorMap = {
        '价值客户': '#52c41a',
        '发展客户': '#1890ff',
        '保持客户': '#faad14',
        '挽留客户': '#f5222d'
      };
      return colorMap[segment] || '#d9d9d9';
    };

    const handleResize = () => {
      if (myChart) {
        myChart.resize();
      }
    };

    const updateChart = () => {
      if (viewType.value === 'chart') {
        setTimeout(() => {
          initChart();
        }, 50);
      }
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
      setTimeout(() => {
        initChart();
      }, 100);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (myChart) {
        myChart.dispose();
      }
    });

    watch(() => viewType.value, () => {
      updateChart();
    });

    watch(() => props.chartData, () => {
      updateChart();
    }, { deep: true });

    return {
      chart,
      viewType,
      tableData,
      totalUsers,
      highValueUsers,
      getSegmentClass,
      getUserSegmentClass,
      updateChart
    };
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.chart-container {
  width: 100%;
  margin: 20px 0;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-header h3 {
  margin: 0;
  color: #333;
}

.controls {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.analysis-type-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.analysis-type-selector label {
  font-weight: bold;
  color: #666;
  white-space: nowrap;
}

.analysis-type-selector select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  min-width: 120px;
}

/* 表格样式 */
.rf-table {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 15px;
}

.table-header h4 {
  margin: 0;
  color: #333;
}

.table-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.table-stats span {
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-scroll-wrapper {
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.rf-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  min-width: 400px;
}

.rf-table th,
.rf-table td {
  padding: 10px;
  text-align: center;
  border: 1px solid #eaeaea;
}

.rf-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  position: sticky;
  top: 0;
}

/* 用户行样式 */
.user-high-value {
  background-color: #f6ffed;
}

.user-active {
  background-color: #e6f7ff;
}

.user-loyal {
  background-color: #fff7e6;
}

.user-churn-risk {
  background-color: #fff1f0;
}

/* 细分统计样式 */
.segment-stats {
  margin-top: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.segment-stats h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.stat-card {
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: white;
}

.stat-card.high-value {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.stat-card.active {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
}

.stat-card.loyal {
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.stat-card.churn-risk {
  background: linear-gradient(135deg, #f5222d, #ff4d4f);
}

.stat-card.general {
  background: linear-gradient(135deg, #fa8c16, #ffa940);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  margin-bottom: 5px;
  opacity: 0.9;
}

.stat-percentage {
  font-size: 14px;
  font-weight: bold;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .controls {
    flex-direction: column;
    gap: 10px;
    width: 100%;
  }
  
  .analysis-type-selector {
    width: 100%;
  }
  
  .analysis-type-selector select {
    flex-grow: 1;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .table-stats {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
}
</style>
